#region " LICENSE "
// DRILL - Dependency Resolution Interface Layer Library
// Copyright (c) 2008-2012 Wade A. Reynolds. All rights reserved.
// http://drill.codeplex.com/
// 
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
// 
// The above copyright notice and this permission notice shall be included in
// all copies or substantial portions of the Software.
// 
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
// THE SOFTWARE.
#endregion
using System;
using System.Collections.Generic;
using System.Configuration;
using System.IO;
using System.Linq;
using Drill.Configuration.ConfigFile;
using Drill.Core;
using Drill.Core.Utilities;

namespace Drill.Configuration
{
	public class ConfigurationHelper : IConfigurationHelper
	{
		private readonly IList<ISearchPath> _searchPaths;
		private readonly IList<IRootPathProvider> _rootPathProviders;

		public ConfigurationHelper(IList<IRootPathProvider> rootPathProviders, IList<ISearchPath> searchPaths = null)
		{
			if (null == rootPathProviders)
			{
				throw new ArgumentNullException("rootPathProviders");
			}

			if (rootPathProviders.Count < 1)
			{
				throw new ArgumentException(
					string.Format("The rootPathProviders list is empty. The rootPathProviders list must contain at least one {0}.", typeof(IRootPathProvider).Name)
				  , "rootPathProviders"
					);
			}

			_searchPaths = searchPaths;
			_rootPathProviders = rootPathProviders;
		}

		/// <summary>
		/// Retrieves the specified config section from the default app or web config file.
		/// </summary>
		/// <returns>An instance of the <see cref="ConfigurationSection"/> class.</returns>
		public virtual T GetConfigSectionFromConfigFile<T>() where T : BaseConfigurationSection, new()
		{
			return ConfigurationUtility.GetConfigSectionFromConfigFile(new T().ConfigSectionName) as T;
		}

		/// <summary>
		/// Retrieves the specified config section from the specified config file.
		/// </summary>
		/// <param name="filename">The filename of the config file containing the secified config section.</param>
		/// <returns>An instance of the <see cref="ConfigurationSection"/> class.</returns>
		public virtual T GetConfigSectionFromConfigFile<T>(string filename) where T : BaseConfigurationSection, new()
		{
			return ConfigurationUtility.GetConfigSectionFromConfigFile(new T().ConfigSectionName, filename) as T;
		}

		/// <summary>
		/// Retrieves the specified config section from the default app or web config file.
		/// </summary>
		/// <param name="configSectionName">The name of the config section to be retrieved.</param>
		/// <returns>An instance of the <see cref="ConfigurationSection"/> class.</returns>
		public virtual ConfigurationSection GetConfigSectionFromConfigFile(string configSectionName)
		{
			return ConfigurationUtility.GetConfigSectionFromConfigFile(configSectionName);
		}

		/// <summary>
		/// Retrieves the specified config section from the specified config file.
		/// </summary>
		/// <param name="configSectionName">The name of the config section to be retrieved.</param>
		/// <param name="filename">The filename of the config file containing the secified config section.</param>
		/// <returns>An instance of the <see cref="ConfigurationSection"/> class.</returns>
		public virtual ConfigurationSection GetConfigSectionFromConfigFile(string configSectionName, string filename)
		{
			return ConfigurationUtility.GetConfigSectionFromConfigFile(configSectionName, filename);
		}

		///<summary>
		/// Loads the configuration from the specified config file.
		///</summary>
		///<param name="filename">The absolute path and file name of the config file to be loaded.</param>
		///<returns>An instance of the <see cref="Configuration" /> class loaded from the specified config file.</returns>
		public virtual System.Configuration.Configuration LoadConfigFile(string filename)
		{
			return ConfigurationUtility.LoadConfigFile(filename);
		}

		/// <summary>
		/// Finds the valid absolute path of the specified file name.
		/// </summary>
		/// <param name="filename">The file name to be resolved. May be a relative path part or an absolute file name.</param>
		/// <returns>
		/// The absolute path of the file or null if the absolute path cannot be determined.
		/// </returns>
		/// <remarks>
		///		If the <paramref name="filename" /> is an absolute path, it is simply returned.
		///		This method uses the configured implementations of the
		///		<see cref="IRootPathProvider" /> interface to obtain a list of
		///		valid root paths that may contain the configuration file.
		///		The first directory that contains the requested <paramref name="filename" />
		///		will be used to construct the absolute filename that is returned.
		///		<para>
		///			The <paramref name="filename" /> can be a simple file name or even a relative
		///			path fragment that includes directory and file name information such as
		///			<example>Config\SomeSpecialConfigDirectory\MyConfigFile.ext</example>.
		///		</para>
		/// </remarks>
		public virtual string FindAbsolutePath(string filename)
		{
			if (string.IsNullOrWhiteSpace(filename))
			{
				throw new ArgumentNullException("filename");
			}

			// If the filename is absolute and exists, simply return it.
			if (Path.IsPathRooted(filename) && File.Exists(filename))
			{
				return filename;
			}

			// Create the locations list and add the default location, the specified filename.
			List<string> locations = new List<string> { filename };
			
			// Add additional locations.
			if (null != _searchPaths && _searchPaths.Count > 0)
			{
				foreach (ISearchPath item in _searchPaths)
				{
					// SearchPaths are usually path fragments but it is 
					// possible for it to be an absolute path or filename.
					// If the searchPath is absolute and exists, return it.
					string searchPath = item.Value;
					if (Path.IsPathRooted(searchPath) && File.Exists(searchPath))
					{
						return searchPath;
					}

					string location = PathUtility.Combine(searchPath, filename);

					// If the location is absolute and exists, return it.
					if (Path.IsPathRooted(location) && File.Exists(location))
					{
						return location;
					}
					locations.Add(location);
				}
			}

			// At this point, the locations list contains non-absolute path fragments that must be resolved.

			List<string> rootPaths = new List<string>();
			foreach (IRootPathProvider rootPathProvider in _rootPathProviders)
			{
				IList<string> paths = rootPathProvider.GetRootPaths();
				if (null != paths && paths.Count > 0)
				{
					rootPaths.AddRange(paths);
				}
			}

			// Return the first combination of an root path and location where the file exists.
			return rootPaths.Select(
				directory => locations.Select(
					location => PathUtility.ResolveRelativePathParts(PathUtility.Combine(directory, location))
					).FirstOrDefault(File.Exists)
				).FirstOrDefault();
		}
	}
}